<template>
  <div class="accessory-item-container">
    <div v-if="isInlineLayout" class="summary-container">
      <i :class="['syIcon', isDoc ? 'sy-associated_document' : 'sy-attachment']" />
    </div>
    <ul :class="{ 'file-list-container': isInlineLayout }">
      <li
        v-for="(item, index) in dataList"
        :key="item.fileUrl"
        class="item-wrapper"
      >
        <section class="left-item-wrapper">
          <span v-if="item.type !== 1" :class="['file-icon', createFileIconString(item)]" />
          <span v-if="isShowSecret" class="secret">{{ getSecret(item.secretLevel) }}</span>
          <section class="title-wrapper">
            <a-tooltip :title="item.filename">
              <NameElement :file="item" class="name-wrapper" />
            </a-tooltip>
            <span v-if="!isDoc">({{ getFileSize(item.size) }})</span>
          </section>
        </section>
        <section class="right-item-wrapper">
          <icon-font
            v-if="item.isUploading || isCreated"
            type="sy-delete-x"
            :title="$i18n('link.jsp.del')"
            class="delete-icon"
            @click="deleteItem(item, index)"
          />
          <div
            v-if="item.isUploading"
            class="progress-bg"
            :style="`width: ${item.process}%`"
          />
          <FileHandle
            v-if="isShowHandle"
            :file="item"
          />
        </section>
      </li>
    </ul>
  </div>
</template>
<script>
  /* global fileUploadAttachments */
  import NameElement from './components/name-element';
  import FileHandle from './components/file-handle';
  // 引入回显关联文档对象操作
  import { addDataList, createID, createAttachment } from '@/helper/relation-doc';
  import { useBaseInfoWithOut } from "@/store/modules/base-info";

  const useBaseInfo = useBaseInfoWithOut();

  export default {
    name: 'AccessoryItem',
    components: {
      NameElement,
      FileHandle,
    },
    props: {
      // 传递的数据列表
      dataList: {
        type: Array,
      },
      // 是否是关联文档
      isDoc: {
        type: Boolean,
        default: false,
      },
      // 关联文档区域名称,用于关联文档选择数据回显
      areaName: {
        type: String,
        default: 'doc1',
      },
      isCreated: { // 是否为创建态
        type: Boolean,
        default: true,
      },
      isInlineLayout: { // 是否横向排列
        type: Boolean,
        default: true,
      },
    },
    computed: {
      isShowHandle() {
        return !this.isDoc && !this.isCreated;
      },
      attachmentReady() {
        return this.dataList.map(item => item.process);
      },
      isShowSecret() {
        return !useBaseInfo.baseInfo.secretLevel.hidden;
      },
    },
    watch: {
      attachmentReady(val) {
        const flag = this.dataList.some(item => item.isUploading && item.process !== 100);

        if (flag) {
          if (!useBaseInfo.attachmentUploading) {
            useBaseInfo.attachmentUploading = true;
            console.log('附件正在上传', val);
          }
        } else {
          useBaseInfo.attachmentUploading = false;
          console.log('附件正上传完成', val);
        }
      },
    },
    mounted() {
      // 如果是关联文档，那么就填入全局对象，以便再选文档的时候回显
      if (this.isDoc && this.dataList.length) {
        addDataList(createAttachment(this.dataList, this.areaName), this.areaName);
      }
    },
    methods: {
      /**
       * @description: 生成文件图标
       * @param {Object} item 当前文件对象
       * @return {String} 返回图标类名
       */
      createFileIconString(item) {
        // 致信的做特殊判断
        if (item.mimeType === 'uc') {
          return 'syDoc zhi_chat';
        }
        // 关联文档用老图标。修改附件的回来没有iconFont属性。也只有用老图标
        if (this.isDoc || !item.iconFont) {
          return `ico16 ${item.icon.split('.')[0]}_16`;
        }

        return `syDoc ${item.iconFont || 'defaultICON'}`;
      },
      /**
       * @description: 删除附件/关联文档
       * @param {String}fileUrl 当前删除项目用于在file那个对象上面删除的索引
       * @param {String}filename 当前删除项目名称
       * @param {Boolean}isUploading 当前删除项目是否为正在上传项目
       * @param {Function}cancel 正在上传项目取消上传
       * @param {Number}index 当前删除项目索引
       */
      deleteItem({ fileUrl, filename, isUploading, cancel }, index) {
        // 如果是删除正在上传的临时文件（附件用）
        if (isUploading) {
          // 取消上传
          cancel();
          // 删除当前项
          this.$emit('deleteItem', index);
          return;
        }

        // 删除已上传文件
        this.$confirm({
          content: this.$i18n(
            this.isDoc ? 'assdoc.isdeletesomeone.mesg' : 'cap.template.common.text.Formsonprompt02',
            filename,
          ),
          okText: this.$i18n('common.button.ok.label'),
          okType: 'danger',
          cancelText: this.$i18n('enum.cancel'),
          onOk: () => {
            // 从界面移除
            this.$emit('deleteItem', index);
            if (this.isDoc) {
              // 从回显用文件对象移除
              fileUploadAttachments.remove(createID(this.areaName, fileUrl));
            }
          },
        });
      },
      getFileSize(size, unit = 'K') {
        /*
         * 1024byte = 1K，1024K = 1M
         * 文件大小单位为 byte，先转化为 K，若超过 1024K，则再继续转化为 M。目前暂不考虑 G
         */
        if (!size && size !== 0) return;
        
        let fileSize = size / 1024;

        if (fileSize < 1024) {
          if (String(fileSize).indexOf('.') === -1) return `${fileSize}${unit}`; // 整除的情况下，直接返回

          fileSize = fileSize.toFixed(1); // 四舍五入保留1位小数
          const [intNum, decimalNum] = fileSize.split('.');

          if (decimalNum === '0') return `${intNum}${unit}`; // 'xxx.0'的情况下，应该返回整数部分

          return `${fileSize}${unit}`;
        }

        return this.getFileSize(fileSize, 'M');
      },
      // 密级
      getSecret(secretLevel) {
        if (!secretLevel) return '';

        const secretInfo = useBaseInfo.baseInfo.secretLevel.options.find(item => item.value === secretLevel) || {};

        return secretInfo.name ? `[${secretInfo.name}]` : '';
      },
    },
  };
</script>
<style lang="scss" scoped>
  .accessory-item-container {
    display: flex;
    align-items: flex-start;

    > .summary-container {
      margin-top: 6px;
      height: 23px;
      display: flex;
      align-items: center;

      > .syIcon {
        color: #999;
      }
    }

    > ul {
      flex: 1;
      overflow: hidden;

      > .item-wrapper {
        position: relative;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 23px;
        padding: 0 8px;
        margin-top: 4px;
        background-color: #F5F7FA;
        border-radius: 3px;

        > .left-item-wrapper {
          display: flex;
          align-items: center;
          overflow: hidden;
          margin-right: 6px;

          > .file-icon {
            font-size: 14px;
            margin-right: 4px;
            width: 14px;
            height: 14px;
          }

          > .secret {
            color: #ff4141;
            margin-right: 2px;
            font-size: 12px;
          }

          > .title-wrapper {
            flex: 1;
            overflow: hidden;
            display: flex;
            align-items: center;
            font-size: 12px;

            > .name-wrapper {
              flex: 1;
            }
          }
        }

        > .right-item-wrapper {
          display: flex;
          align-items: center;

          > .delete-icon {
            color: #8C8C8C;
            font-size: 14px;
            cursor: pointer;
          }
          
          > .progress-bg {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 1px;
            background-color: $primary-color;
            opacity: 0.5;
            transition: width $tn linear;
          }
        }
      }
    }

    > ul.file-list-container {
      display: flex;
      flex-wrap: wrap;

      > .item-wrapper {
        width: 260px;
        margin-left: 10px;
      }
    }
  }
</style>
